<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <div>
      <button id="btnBatch">批量创建</button>
      <button id="btnSingle">单独创建</button>
    </div>
    <div id="root" style="height: 500px; overflow: auto"></div>

    <script type="text/javascript">
      const items = Array.from({ length: 100000 }, (v, i) => ({
        name: "name" + i,
        age: i,
        sex: i % 2,
      }));

      const rootEl = document.getElementById("root");
      function createByS() {
        console.time("单独创建");
        items.forEach(function (item) {
          const div = document.createElement("div");
          div.innerHTML = `name:${item.name} - age: ${item.age} - sex: ${item.sex}`;
          rootEl.appendChild(div);
        });
        console.timeEnd("单独创建");
      }

      function createByB() {
        console.time("批量创建");
        const fragment = document.createDocumentFragment();
        items.forEach(function (item) {
          const div = document.createElement("div");
          div.innerHTML = `name:${item.name} - age: ${item.age} - sex: ${item.sex}`;
          fragment.appendChild(div);
        });
        rootEl.appendChild(fragment);
        console.timeEnd("批量创建");
      }

      btnBatch.addEventListener("click", createByB);
      btnSingle.addEventListener("click", createByS);
    </script>
  </body>
</html>
